<?php
class Model{

	public $_db;

	private static $_instance;

	public function __construct( $config ){
		$this->_db =  new BaseDb($config);
	}

	public static function setDb( Model $model ){
		self::$_instance = $model;
	}

	public static function getDb(){
		if (!empty(self::$_instance))
			return self::$_instance;
		else
			echo 'db error';
			exit;
	}

	/**
	 * insert database;
	 * @param table
	 * @param options
	 * return 1/0;
	 */
	protected function insert( $table, $options){
		$sql = "INSERT INTO ".$table;
		$sql_pre = "";
		$sql_ext = "";
		$count = count($options);

		if(is_array($options) && $count > 0){
			$i = 0;
			foreach($options as $key=>$val){
				$i++;
				$sql_pre .= '`'.$key.'`';
				$sql_ext .= "?";
				if($i < $count ){
					$sql_pre .= ',';
					$sql_ext .= ',';
				}
			}
			$sql = $sql.'('.$sql_pre.') VALUES('.$sql_ext.')';
			$this->getDb()->_db->query($sql, $options);
			return $this->getDb()->_db->insert();
			
		}else{
			return 0;
		}

	}

	/**
	 * multi_insert database;
	 * @param table
	 * @param options
	 * return 1/0;
	 */
	protected function multi_insert( $table, $options){
		$sql = "INSERT INTO ".$table;
		$sql_pre = "";
		$sql_ext = "";


		if(is_array($options) && count($options) > 0){
			$prefix = implode(",", array_keys($options[0]));

			$param = array();
			foreach($options as $v){
				 $mask[] = '('.$this->placefield('?', count($v)).')';
				 $param = array_merge( $param, array_values($v) );
			}
			$ext = implode(',', $mask);

			$sql .= '('.$prefix.') VALUES '.$ext;
			$this->getDb()->_db->query($sql, $param, 1);
			return $this->getDb()->_db->insert();
			
		}else{
			return 0;
		}
	}

	private function placefield($text, $count=0, $separator=","){
		$result = array();
		if($count > 0){
			for($x=0; $x<$count; $x++){
				$result[] = $text;
			}
		}
		return implode($separator, $result);
	}

}
